/* eslint-disable @typescript-eslint/no-base-to-string */
/* eslint-disable @typescript-eslint/restrict-template-expressions */
import {
  utilities as nestWinstonModuleUtilities,
  WinstonModule,
} from 'nest-winston';
import * as winston from 'winston';
import 'winston-daily-rotate-file';
import * as path from 'path';

// 日志文件路径
const logDir = path.join(process.cwd(), 'logs');

// 定义日志格式
const logFormat = winston.format.combine(
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
  winston.format.printf(
    (info) =>
      `${info.timestamp} [${info.level}] [${info.context || 'Application'}] - ${info.message}`,
  ),
);

// 控制台日志格式
const consoleFormat = winston.format.combine(
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
  winston.format.colorize(),
  nestWinstonModuleUtilities.format.nestLike('AI-Web', { prettyPrint: true }),
);

// 确保日志目录存在
import * as fs from 'fs';
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

// 创建日志传输器
const transports = [
  // 控制台日志
  new winston.transports.Console({
    format: consoleFormat,
  }),
  // 信息日志文件 - 按日期轮转
  new winston.transports.DailyRotateFile({
    dirname: logDir,
    filename: 'application-%DATE%.log',
    datePattern: 'YYYY-MM-DD',
    maxSize: '20m',
    maxFiles: '14d',
    format: logFormat,
    level: 'info',
  }),
  // 错误日志文件 - 按日期轮转
  new winston.transports.DailyRotateFile({
    dirname: logDir,
    filename: 'error-%DATE%.log',
    datePattern: 'YYYY-MM-DD',
    maxSize: '20m',
    maxFiles: '14d',
    format: logFormat,
    level: 'error',
  }),
  // HTTP请求日志文件 - 按日期轮转
  new winston.transports.DailyRotateFile({
    dirname: logDir,
    filename: 'http-%DATE%.log',
    datePattern: 'YYYY-MM-DD',
    maxSize: '20m',
    maxFiles: '14d',
    format: logFormat,
    level: 'http',
  }),
  // 调试日志文件 - 按日期轮转
  new winston.transports.DailyRotateFile({
    dirname: logDir,
    filename: 'debug-%DATE%.log',
    datePattern: 'YYYY-MM-DD',
    maxSize: '20m',
    maxFiles: '7d',
    format: logFormat,
    level: 'debug',
  }),
];

// 创建Winston日志实例
export const winstonLoggerConfig = {
  transports,
  // 默认日志级别
  level: process.env.NODE_ENV !== 'production' ? 'debug' : 'info',
};

// 导出NestJS可用的日志模块
export const logger = WinstonModule.createLogger(winstonLoggerConfig);
